package com.lizk.tools.hotdeploy;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ClassLoadUtil implements Runnable{
	URLClassLoader cl = null; 
	CheckClassChangeUtil checkClassChangeUtil = null;
	String path = null;
	
	public ClassLoadUtil(String path){
		this.path = path;
		checkClassChangeUtil = new CheckClassChangeUtil(path);
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		service.scheduleWithFixedDelay(this, 0, 5, TimeUnit.SECONDS);
	}
	
	
	public Object exeClazz(String ClazzName,String methodName,Object[] objects){
		Object object = null;
		try {
			Class<?> clazz = cl.loadClass(ClazzName);
			Object ob = clazz.newInstance();
			Method method = clazz.getMethod(methodName);
			object = method.invoke(ob,objects);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return object;
	}
	
	
	@Override
	public void run() {
		
		if(checkClassChangeUtil.checkAllFile()){
			System.out.println("重新加载");
			try {
				cl=new URLClassLoader(new URL[]{new File(path).toURI().toURL()});
				checkClassChangeUtil.reSetIsChange();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}
	}
	
}
